package com.cyf.filmDownload.m3u8.task;

import com.cyf.filmDownload.common.util.FileUtil;
import com.cyf.filmDownload.m3u8.entity.DownloadProgress;
import com.cyf.filmDownload.m3u8.entity.M3u8ParserResult;
import com.cyf.filmDownload.m3u8.entity.VideoTs;
import com.cyf.filmDownload.m3u8.exception.M3u8Exception;
import com.cyf.filmDownload.okhttp.HttpUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Files;

@Data
@Slf4j
public class DownloadTask implements Runnable {

    private VideoTs ts;

    private M3u8ParserResult parserResult;

    private DownloadProgress downloadProgress;

    public DownloadTask(){
    }

    public DownloadTask(VideoTs ts, M3u8ParserResult parserResult, DownloadProgress downloadProgress) {
        this.ts = ts;
        this.parserResult = parserResult;
        this.downloadProgress = downloadProgress;
    }

    @Override
    public void run() {
        File tsFile = new File(ts.getFilePath());
        if (tsFile.exists()) {
            downloadProgress.increaseFinish();
            return;
        }
        try(Response response = HttpUtil.get(ts.getUrl())) {
            if (!response.isSuccessful()) {
                throw new M3u8Exception(ts.getFileName() + "视频分片下载失败");
            }
            byte[] bytes = response.body().bytes();
            // 对视频解密
            if (parserResult.isEncrypt()) {
                bytes = decrypt(bytes, parserResult.getEncryptMethod(), parserResult.getKeyByte(), parserResult.getIvByte());
            }
            FileUtil.writeBytesToFile(ts.getFilePath(), bytes);
        } catch (Exception e) {
            throw new M3u8Exception(ts.getFileName() + "视频分片下载失败", e);
        } finally {
            downloadProgress.increaseFinish();
        }
    }

    /**
     * 解密ts
     *
     * @param tsBytes ts文件字节数组
     * @param method  加密方法
     * @param keyByte 密钥
     * @param ivByte  初始化向量
     * @return 解密后的字节数组
     */
    public static byte[] decrypt(byte[] tsBytes, String method, byte[] keyByte, byte[] ivByte) {
        if (StringUtils.isNotEmpty(method) && !method.contains("AES")) {
            throw new M3u8Exception("未知的加密算法");
        }
        if (keyByte.length != 16) {
            throw new M3u8Exception("key长度不是16位");
        }
        try {
            // 根据加密算法获取加密器
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            // 将AES密钥转换为SecretKeySpec对象
            SecretKeySpec secretKeySpec = new SecretKeySpec(keyByte, "AES");
            // 将AES初始化向量转换为IvParameterSpec对象
            IvParameterSpec ivParameterSpec = new IvParameterSpec(ivByte);
            // 初始化解密器，设置解密模式、密钥和初始化向量
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
            // 解密数据
            return cipher.doFinal(tsBytes);
        } catch (Exception e) {
            throw new M3u8Exception("ts解密失败", e);
        }
    }
}